package com.rc.saas.mini.service.recharge;

import com.alibaba.fastjson.JSON;
import com.rc.saas.mini.common.constant.HttpConstant;
import com.rc.saas.mini.common.mq.MqConfig;
import com.rc.saas.mini.common.mq.MqProducer;
import com.rc.saas.mini.common.utils.RedisUtil;
import com.rc.saas.mini.mapper.member.MemberAccountMapper;
import com.rc.saas.mini.mapper.member.MemberAccountRecordMapper;
import com.rc.saas.mini.mapper.recharge.RechargeOrderMapper;
import com.rc.saas.mini.model.member.*;
import com.rc.saas.mini.model.rc.*;
import com.rc.saas.mini.model.recharge.RechargeOrder;
import com.rc.saas.mini.model.recharge.RechargeOrderExample;
import com.rc.saas.mini.model.tenant.TenantTransfer;
import com.rc.saas.mini.model.tenant.TenantTransferExample;
import com.rc.saas.mini.service.market.MarketActivityService;
import com.rc.saas.mini.service.member.*;
import com.rc.saas.mini.service.order.OrderRefundApplyService;
import com.rc.saas.mini.service.rc.*;
import com.rc.saas.mini.service.tenant.TenantTransferService;
import com.rc.saas.mini.vo.member.CurrentMemberFlagAllVo;
import com.rc.saas.mini.vo.rc.RcMemberLevelVo;
import com.rc.saas.mini.vo.recharge.RechargeOrderVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author wangzhengwei
 * @create 2021/4/29
 */
@Service
public class RechargeOrderServiceImpl implements RechargeOrderService {
    Logger logger = LoggerFactory.getLogger(RechargeOrderServiceImpl.class);

    @Autowired
    private RechargeOrderMapper rechargeOrderMapper;

    @Autowired
    private MemberInfoService memberInfoService;

    @Autowired
    private MemberAccountMapper memberAccountMapper;

    @Override
    public RechargeOrderMapper getMapper() {
        return rechargeOrderMapper;
    }

    @Autowired
    private MemberAccountRecordMapper memberAccountRecordMapper;

    @Autowired
    private MemberAccountRecordService memberAccountRecordService;

    @Autowired
    private RcMemberFlagService rcMemberFlagService;

    @Autowired
    private MarketActivityService marketActivityService;
    @Autowired
    private RcMemberLevelSettingService rcMemberLevelSettingService;

    @Autowired
    private MemberTicketService memberTicketService;

    @Autowired
    private MemberRefundOrderService memberRefundOrderService;

    @Autowired
    private RcMemberGainSettingService rcMemberGainSettingService;

    @Autowired
    private RcMemberGainGradeSettingService rcMemberGainGradeSettingService;

    @Autowired
    private RcMemberGainRecordService rcMemberGainRecordService;
    @Autowired
    private RcMemberGainSettingRecordService rcMemberGainSettingRecordService;

    @Autowired
    private RcMemberGainGradeRecordService rcMemberGainGradeRecordService;

    @Autowired
    private MemberRefundApplyService memberRefundApplyService;

    @Autowired
    private MqProducer mqProducer;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private RcSettingService rcSettingService;

    @Autowired
    private OrderRefundApplyService orderRefundApplyService;

    @Autowired
    private TenantTransferService tenantTransferService;

    @Override
    public RechargeOrderVo selectRechargeOrderByOutTradeNo(String outTradeNo) {
        return rechargeOrderMapper.selectRechargeOrderByOutTradeNo(outTradeNo);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public synchronized boolean updateRechargeOrder(Long rechargeOrderId, String paymentType, String transaction_id) {
        //获取微信充值订单
        RechargeOrder rechargeOrder = rechargeOrderMapper.selectByPrimaryKey(rechargeOrderId);
        //保证原子性
        if (!redisUtil.setIfAbsent("rechargeOrderId:" + rechargeOrderId, "1", 5000L)) {
            logger.info("订单到账,rechargeOrderId:{},不能重复执行!!", rechargeOrderId);
            return false;
        }
        //查找用户信息
        MemberInfo member = memberInfoService.selectByPrimaryKey(rechargeOrder.getMemberId());
        //到帐状态 0未到帐 1已到帐 默认0
        if (null != rechargeOrder && (!HttpConstant.STATUS_ONE.equals(rechargeOrder.getStatus()))) {
            Date date = new Date();

            //1 修改充值单状态
            RechargeOrder updateRechargeOrder = new RechargeOrder();
            updateRechargeOrder.setRechargeOrderId(rechargeOrderId);


            ////填加减免记录,检测减免情况
            //boolean reduction=memberTicketService.intsertCurrentReductionActivity(member, rechargeOrder);
            //if(rechargeOrder.getFactAmount().compareTo(rechargeOrder.getAmount())!=0){
            //    //充值和实付不一致
            //    if(!reduction){
            //        logger.warn("减免失败，到账金额修改为实付金额:实付从：{}改为：{}", rechargeOrder.getAmount(),rechargeOrder.getFactAmount());
            //        rechargeOrder.setAmount(rechargeOrder.getFactAmount());
            //    }
            //}

            updateRechargeOrder.setTransactionId(transaction_id);
            updateRechargeOrder.setStatus(HttpConstant.STATUS_ONE);
            updateRechargeOrder.setFinishTime(date);
            rechargeOrderMapper.updateByPrimaryKeySelective(updateRechargeOrder);

            MemberAccount memberAccount = memberAccountMapper.selectByPrimaryKey(rechargeOrder.getMemberId());
            //取此时的原始账户，是为了填补上次超充导致的账户负数
            BigDecimal originalAccount = memberAccount.getAccount();
            if (memberAccount == null) {
                logger.error("找不到会员余额记录:{}", rechargeOrder.getMemberId());
                throw new RuntimeException("找不到会员余额记录");
            }

            //推荐者权益增加（渠道商）
            recommenderChannelAdd(memberAccount, rechargeOrder);

            MemberAccount updateMemberAccount = new MemberAccount();
            updateMemberAccount.setMemberId(rechargeOrder.getMemberId());
            //余额累计
            updateMemberAccount.setAccount(rechargeOrder.getAmount());
            updateMemberAccount.setGiveAccount(rechargeOrder.getGiveAmount());
            updateMemberAccount.setLastUpdatedTime(date);
            //充值累计
            updateMemberAccount.setAllRechargeAmount(rechargeOrder.getAmount());

            updateMemberAccount.setVersion(memberAccount.getVersion());
            //            memberAccountMapper.updateMemberAccountByMemberId(updateMemberAccount);

            int i = memberAccountMapper.updateMemberAccountByLock(updateMemberAccount);
            if (i == 0) {
                //版本不一致，回退
                mqProducer.send(MqConfig.LOCK_MINI_RESET_RECHARGE_ORDER_QUEUE, "", 2000);
                logger.info("充值单乐观锁被占用！！,对应用户手机号码:{},充值单ID：{}", member.getMobile(), rechargeOrder.getRechargeOrderId());
                throw new RuntimeException("充值单锁被占用！！，将重新入账充值单,对应用户手机号码:" + member.getMobile());
            }

            //3 新增余额变动记录
            MemberAccountRecord memberAccountRecord = new MemberAccountRecord();
            memberAccountRecord.setTenantCode(rechargeOrder.getTenantCode());
            memberAccountRecord.setMemberId(rechargeOrder.getMemberId());
            memberAccountRecord.setLocalTradeNo(rechargeOrder.getOutTradeNo());

            //支付的账户类型 0个人钱包 1 企业钱包 2权益金 3收益金
            memberAccountRecord.setAccountType("0");

            //记录类型(0会员在线充值,1支出,2转账收入,3分配余额,4后台订单调整,5平台赠送,6积分兑换 7回收金额 8平台钱包充值 9分销返利 10资源占用费 11平台扣费 12 数据迁移 13共享额度变更 14后台退款 15.原路退款 16原路返还 ) 17.先付后退充值 18.先付后退退款
            String recordType = "0";
            memberAccountRecord.setRecordType(recordType);

            //本次变更金额
            memberAccountRecord.setAmount(rechargeOrder.getAmount());

            //累计后的account
            BigDecimal result = originalAccount.add(rechargeOrder.getAmount());
            memberAccountRecord.setResult(result);

            StringBuffer sb = new StringBuffer("充值");
            if (rechargeOrder.getAmount().compareTo(rechargeOrder.getFactAmount()) != 0) {
                sb.append("减免");
            }
            memberAccountRecord.setRemark(sb.toString());
            memberAccountRecord.setCreatedTime(date);
            memberAccountRecord.setLastUpdatedTime(date);
            memberAccountRecordMapper.insertByReturnId(memberAccountRecord);
            // 发送mq 给后台
            mqProducer.send(MqConfig.app_rc_operator_account_record, JSON.toJSONString(memberAccountRecord));
            logger.info("充值入账成功,tenantCode:{},memberId:{},outTradeNo:{},支付金额:{},入账金额,:{},新的余额,:{}", rechargeOrder.getTenantCode(), rechargeOrder.getMemberId(), rechargeOrder.getOutTradeNo(), rechargeOrder.getFactAmount(), rechargeOrder.getAmount(), result);
            //实际支付金额发放优惠券
            //marketActivityService.sendChargeTicketByMarketActivity(rechargeOrder.getMemberId(),rechargeOrder.getFactAmount(),rechargeOrder.getTenantCode(),"1", rechargeOrderId);

            //添加优惠券
            memberTicketService.insertActivityTicket(member, rechargeOrder);

            //添加额度变更记录
            memberRefundOrderService.insertByRechargeOrder(rechargeOrderId, recordType, originalAccount);


            //MemberAccount memberAccountNew = memberAccountMapper.selectByPrimaryKey(member.getMemberId());

            //RcMemberFlag rcMemberFlag = rcMemberFlagService.selectByPrimaryKey(member.getMemberId());
            //if (rcMemberFlag.getMemberLevel() == null || "V0".equals(rcMemberFlag.getMemberLevel())) {
            //首次充值/V0 需要达到等级，V1会员及其上之后是累计的(废弃)
            rcMemberLevelSettingAdd(rechargeOrder);
            //} else {
            //    累计充值，会员权益变更
            //rcMemberLevelSettingAdd(memberAccountNew, rechargeOrder);
            //}

            //权益金增加
            frozenGiveAccountAdd(rechargeOrder);
            try {
                //参与充值活动
                marketActivityService.rechangerMember(rechargeOrder.getMemberId(), rechargeOrder);
            } catch (Exception e) {
                e.printStackTrace();
            }

            return true;
        }
        return false;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public synchronized boolean updateRechargeOrderRefund(Long rechargeOrderId, String paymentType, String transaction_id) {
        //获取微信充值订单
        RechargeOrder rechargeOrder = rechargeOrderMapper.selectByPrimaryKey(rechargeOrderId);

        //查找用户信息
        MemberInfo member = memberInfoService.selectByPrimaryKey(rechargeOrder.getMemberId());
        //到帐状态 0未到帐 1已到帐 默认0
        if (null != rechargeOrder && (!HttpConstant.STATUS_ONE.equals(rechargeOrder.getStatus()))) {
            Date date = new Date();

            //1 修改充值单状态
            RechargeOrder updateRechargeOrder = new RechargeOrder();
            updateRechargeOrder.setRechargeOrderId(rechargeOrderId);


            ////填加减免记录,检测减免情况
            //boolean reduction=memberTicketService.intsertCurrentReductionActivity(member, rechargeOrder);
            //if(rechargeOrder.getFactAmount().compareTo(rechargeOrder.getAmount())!=0){
            //    //充值和实付不一致
            //    if(!reduction){
            //        logger.warn("减免失败，到账金额修改为实付金额:实付从：{}改为：{}", rechargeOrder.getAmount(),rechargeOrder.getFactAmount());
            //        rechargeOrder.setAmount(rechargeOrder.getFactAmount());
            //    }
            //}
            updateRechargeOrder.setPaymentProperty("1");
            updateRechargeOrder.setTransactionId(transaction_id);
            updateRechargeOrder.setStatus(HttpConstant.STATUS_ONE);
            updateRechargeOrder.setFinishTime(date);
            rechargeOrderMapper.updateByPrimaryKeySelective(updateRechargeOrder);

            MemberAccount memberAccount = memberAccountMapper.selectByPrimaryKey(rechargeOrder.getMemberId());
            //取此时的原始账户，是为了填补上次超充导致的账户负数
            BigDecimal originalAccount = memberAccount.getPaymentRefundAccount();
            if (memberAccount == null) {
                logger.error("找不到会员余额记录:{}", rechargeOrder.getMemberId());
                throw new RuntimeException("找不到会员余额记录");
            }

            //推荐者权益增加（渠道商）
            //recommenderChannelAdd(memberAccount, rechargeOrder);

            MemberAccount updateMemberAccount = new MemberAccount();
            updateMemberAccount.setMemberId(rechargeOrder.getMemberId());
            //余额累计
            updateMemberAccount.setPaymentRefundAccount(rechargeOrder.getAmount().add(memberAccount.getPaymentRefundAccount()).setScale(2));
            updateMemberAccount.setLastUpdatedTime(date);

            memberAccountMapper.updateByPrimaryKeySelective(updateMemberAccount);

            //3 新增余额变动记录
            MemberAccountRecord memberAccountRecord = new MemberAccountRecord();
            memberAccountRecord.setTenantCode(rechargeOrder.getTenantCode());
            memberAccountRecord.setMemberId(rechargeOrder.getMemberId());
            memberAccountRecord.setLocalTradeNo(rechargeOrder.getOutTradeNo());

            //支付的账户类型 0个人钱包 1 企业钱包 2权益金 3收益金
            memberAccountRecord.setAccountType("4");

            //记录类型(0会员在线充值,1支出,2转账收入,3分配余额,4后台订单调整,5平台赠送,6积分兑换 7回收金额 8平台钱包充值 9分销返利 10资源占用费 11平台扣费 12 数据迁移 13共享额度变更 14后台退款 15.原路退款 16原路返还 ) 17.先付后退充值 18.先付后退退款
            String recordType = "17";
            memberAccountRecord.setRecordType(recordType);

            //本次变更金额
            memberAccountRecord.setAmount(rechargeOrder.getAmount());

            //累计后的account

            memberAccountRecord.setResult(updateMemberAccount.getPaymentRefundAccount());

            StringBuffer sb = new StringBuffer("先付后退充值");
            memberAccountRecord.setRemark(sb.toString());
            memberAccountRecord.setCreatedTime(date);
            memberAccountRecord.setLastUpdatedTime(date);
            memberAccountRecordMapper.insertByReturnId(memberAccountRecord);
            // 发送mq 给后台
            mqProducer.send(MqConfig.app_rc_operator_account_record, JSON.toJSONString(memberAccountRecord));
            logger.info("充值入账成功,tenantCode:{},memberId:{},outTradeNo:{},支付金额:{},入账金额,:{},新的余额,:{}",
                    rechargeOrder.getTenantCode(), rechargeOrder.getMemberId(),
                    rechargeOrder.getOutTradeNo(), rechargeOrder.getFactAmount(), rechargeOrder.getAmount(), updateMemberAccount.getPaymentRefundAccount());
            //实际支付金额发放优惠券
            //marketActivityService.sendChargeTicketByMarketActivity(rechargeOrder.getMemberId(),rechargeOrder.getFactAmount(),rechargeOrder.getTenantCode(),"1", rechargeOrderId);

            //添加优惠券
            //memberTicketService.insertActivityTicket(member, rechargeOrder);

            //添加额度变更记录
            memberRefundOrderService.insertByRechargeOrder(rechargeOrderId, recordType, originalAccount);


            //MemberAccount memberAccountNew = memberAccountMapper.selectByPrimaryKey(member.getMemberId());

            //RcMemberFlag rcMemberFlag = rcMemberFlagService.selectByPrimaryKey(member.getMemberId());
            //if (rcMemberFlag.getMemberLevel() == null || "V0".equals(rcMemberFlag.getMemberLevel())) {
            //首次充值/V0 需要达到等级，V1会员及其上之后是累计的(废弃)
            //rcMemberLevelSettingAdd(rechargeOrder);
            //} else {
            //    累计充值，会员权益变更
            //rcMemberLevelSettingAdd(memberAccountNew, rechargeOrder);
            //}

            //权益金增加
            //frozenGiveAccountAdd(rechargeOrder);
            //try {
            //    参与充值活动
            //marketActivityService.rechangerMember(rechargeOrder.getMemberId(), rechargeOrder);
            //} catch (Exception e) {
            //    e.printStackTrace();
            return true;


        }
        return false;
    }

    @Override
    public RechargeOrder selectByTransactionId(String transaction_id) {
        RechargeOrderExample rechargeOrderExample = new RechargeOrderExample();
        rechargeOrderExample.createCriteria().andTransactionIdEqualTo(transaction_id);
        return rechargeOrderMapper.selectByExample(rechargeOrderExample).stream().findFirst().orElse(null);
    }

    /**
     * 累计充值，会员权益变更
     */
    public void rcMemberLevelSettingAdd(MemberAccount memberAccount, RechargeOrder rechargeOrder) {

        Long memberId = memberAccount.getMemberId();
        RcMemberFlag rcMemberFlag = rcMemberFlagService.selectByPrimaryKey(memberId);

        //其他等级，累加
        MemberAccount addMemberAccount = new MemberAccount();
        addMemberAccount.setMemberId(memberId);
        addMemberAccount.setUpperAmount(memberAccount.getUpperAmount().add(rechargeOrder.getAmount()));
        addMemberAccount.setLastUpdatedTime(new Date());
        memberAccountMapper.updateByPrimaryKeySelective(addMemberAccount);

        BigDecimal amount = addMemberAccount.getUpperAmount();
        RcMemberLevelSetting rcMemberLevelSetting = rcMemberLevelSettingService.selectByMemberAccount(amount);


        if (rcMemberFlag.getMemberLevel() != null && (rcMemberFlag.getMemberLevel().equals(rcMemberLevelSetting.getMemberLevel()) || Integer.valueOf(rcMemberFlag.getMemberLevel().replaceAll("V", "")) >= Integer.valueOf(rcMemberLevelSetting.getMemberLevel().replaceAll("V", "")))) {
            MemberAccount leveMemberAccount = new MemberAccount();
            leveMemberAccount.setMemberId(memberId);
            leveMemberAccount.setMemberLevelAmount(rechargeOrder.getAmount());
            leveMemberAccount.setLastUpdatedTime(new Date());
            memberAccountMapper.updateByPrimaryKeySelective(leveMemberAccount);
            logger.info("用户：{}，会员权益无变更,不需要升级或者变更：{}", memberAccount.getMemberId(), JSON.toJSONString(addMemberAccount));
            return;
        }

        if (rcMemberLevelSetting == null) {
            logger.info("用户：{}，会员权益无变更增加：{}", memberAccount.getMemberId(), JSON.toJSONString(addMemberAccount));
            //return;
        }
        ////默认规则
        //List<RcMemberGainSetting> rcMemberGainSettingList = rcMemberGainSettingService.listByDefaultWithLevelSub(rcMemberLevelSetting.getLevelSub());
        //if (rcMemberGainSettingList == null || rcMemberGainSettingList.size() == 0) {
        //    //无默认取其他规则
        //    logger.info("用户：{}，会员权益无默认规则：{}", memberAccount.getMemberId(), JSON.toJSONString(rcMemberLevelSetting));
        //    //return;
        //}
        //
        //
        //MemberRefundApplyExample memberRefundApplyExample = new MemberRefundApplyExample();
        //memberRefundApplyExample.createCriteria().andStatusEqualTo("4").andMemberIdEqualTo(memberId);
        //List<MemberRefundApply> memberRefundApplyList = memberRefundApplyService.selectByExample(memberRefundApplyExample);
        //
        //
        ////获取挡位
        //List<Long> ids = new ArrayList<>();
        //for (RcMemberGainSetting rcMemberGainSetting : rcMemberGainSettingList) {
        //    if (rcMemberGainSetting.getRefundCountTarget() != null && rcMemberGainSetting.getRefundCountTarget() <= memberRefundApplyList.size()) {
        //        logger.info("用户：{}，查询用户退款次数，不能增加权益：{}", memberAccount.getMemberId(), JSON.toJSONString(rcMemberLevelSetting));
        //        return;
        //    } else {
        //        ids.add(rcMemberGainSetting.getMemberGainId());
        //    }
        //}
        //List<RcMemberGainGradeSetting> rcMemberGainGradeSettingList = new ArrayList<>();
        //
        ////rcMemberGainSettingList.stream().map(RcMemberGainSetting::getMemberGainId).collect(Collectors.toList());
        //if (ids.size() <= 0) {
        //    logger.info("用户：{}，会员权益无可用权益：{}", memberAccount.getMemberId(), JSON.toJSONString(rcMemberLevelSetting));
        //    //return;
        //} else {
        //    rcMemberGainGradeSettingList = rcMemberGainGradeSettingService.listByWithMemberGainIds(ids);
        //}
        //
        //if (rcMemberGainGradeSettingList == null || rcMemberGainGradeSettingList.size() == 0) {
        //    //无默认取其他规则
        //    logger.info("用户：{}，会员权益无挡位：{}", memberAccount.getMemberId(), JSON.toJSONString(rcMemberLevelSetting));
        //    //return;
        //}

        rcMemberFlag.setMemberLevel(rcMemberLevelSetting.getMemberLevel());
        rcMemberFlag.setSubLevel(rcMemberLevelSetting.getLevelSub());
        rcMemberFlag.setIsMemberLevel("1");
        rcMemberFlag.setLastUpdatedTime(new Date());
        //会员权益变更
        rcMemberFlagService.updateByPrimaryKey(rcMemberFlag);

        //权益变更 升级至0
        MemberAccount leveMemberAccount = new MemberAccount();
        leveMemberAccount.setMemberId(memberId);
        leveMemberAccount.setMemberLevelAmount(BigDecimal.ZERO);
        leveMemberAccount.setLastUpdatedTime(new Date());
        memberAccountMapper.updateByPrimaryKeySelective(leveMemberAccount);
        //rcMemberGainRecordService.insertByList(rcMemberGainSettingList, memberId);
        //if (rcMemberGainSettingList.size() > 0) {
        //    //有默认规则自动增加
        //    //rcMemberGainSettingRecordService.insertByList(rcMemberGainSettingList, memberId);
        //}
        //if (rcMemberGainGradeSettingList.size() > 0) {
        //    //挡位增加
        //    //rcMemberGainGradeRecordService.insertByList(rcMemberGainGradeSettingList, memberId);
        //}

        //后续同步空值record下的数据id
        //rcMemberGainGradeRecordService.updateByList();
    }


    /**
     * 单次充值，会员权益变更
     */
    public void rcMemberLevelSettingAdd(RechargeOrder rechargeOrder) {
        Long memberId = rechargeOrder.getMemberId();
        BigDecimal amount = rechargeOrder.getAmount();
        RcMemberLevelSetting rcMemberLevelSetting = rcMemberLevelSettingService.selectByMemberAccount(amount);

        RcMemberFlag rcMemberFlag = rcMemberFlagService.selectByPrimaryKey(memberId);
        if (rcMemberFlag.getMemberLevel() != null && (rcMemberFlag.getMemberLevel().equals(rcMemberLevelSetting.getMemberLevel()) || Integer.valueOf(rcMemberFlag.getMemberLevel().replaceAll("V", "")) >= Integer.valueOf(rcMemberLevelSetting.getMemberLevel().replaceAll("V", "")))) {
            //保存最近一笔额度数据
            MemberAccount leveMemberAccount = new MemberAccount();
            leveMemberAccount.setMemberId(memberId);
            leveMemberAccount.setMemberLevelAmount(rechargeOrder.getAmount());
            leveMemberAccount.setLastUpdatedTime(new Date());
            memberAccountMapper.updateByPrimaryKeySelective(leveMemberAccount);
            logger.info("用户：{}，会员权益无变更,不需要升级或者变更：{}", rechargeOrder.getMemberId(), JSON.toJSONString(rechargeOrder));
            return;
        }

        if (rcMemberLevelSetting == null) {
            logger.info("用户：{}，会员权益无变更增加：{}", memberId, JSON.toJSONString(rechargeOrder));
            return;
        }
        ////默认规则
        //List<RcMemberGainSetting> rcMemberGainSettingList = rcMemberGainSettingService.listByDefaultWithLevelSub(rcMemberLevelSetting.getLevelSub());
        //if (rcMemberGainSettingList == null || rcMemberGainSettingList.size() == 0) {
        //    //无默认取其他规则
        //    logger.info("用户：{}，会员权益无默认规则：{}", memberId, JSON.toJSONString(rcMemberLevelSetting));
        //    //return;
        //}


        //MemberRefundApplyExample memberRefundApplyExample = new MemberRefundApplyExample();
        //memberRefundApplyExample.createCriteria().andStatusEqualTo("4").andMemberIdEqualTo(memberId);
        //List<MemberRefundApply> memberRefundApplyList = memberRefundApplyService.selectByExample(memberRefundApplyExample);


        ////获取挡位
        //List<Long> ids = new ArrayList<>();
        //for (RcMemberGainSetting rcMemberGainSetting : rcMemberGainSettingList) {
        //    if (rcMemberGainSetting.getRefundCountTarget() != null && rcMemberGainSetting.getRefundCountTarget() <= memberRefundApplyList.size()) {
        //        logger.info("用户：{}，查询用户退款次数，不能增加权益：{}", memberId, JSON.toJSONString(rcMemberLevelSetting));
        //        return;
        //    } else {
        //        ids.add(rcMemberGainSetting.getMemberGainId());
        //    }
        //}
        //List<RcMemberGainGradeSetting> rcMemberGainGradeSettingList = new ArrayList<>();
        //
        ////rcMemberGainSettingList.stream().map(RcMemberGainSetting::getMemberGainId).collect(Collectors.toList());
        //if (ids.size() <= 0) {
        //    logger.info("用户：{}，会员权益无可用权益：{}", memberId, JSON.toJSONString(rcMemberLevelSetting));
        //    //return;
        //} else {
        //    rcMemberGainGradeSettingList = rcMemberGainGradeSettingService.listByWithMemberGainIds(ids);
        //}
        //
        //if (rcMemberGainGradeSettingList == null || rcMemberGainGradeSettingList.size() == 0) {
        //    //无默认取其他规则
        //    logger.info("用户：{}，会员权益无挡位：{}", memberId, JSON.toJSONString(rcMemberLevelSetting));
        //    //return;
        //}

        rcMemberFlag.setMemberLevel(rcMemberLevelSetting.getMemberLevel());
        rcMemberFlag.setSubLevel(rcMemberLevelSetting.getLevelSub());
        rcMemberFlag.setIsMemberLevel("1");
        rcMemberFlag.setLastUpdatedTime(new Date());
        //会员权益变更
        rcMemberFlagService.updateByPrimaryKey(rcMemberFlag);

        ////rcMemberGainRecordService.insertByList(rcMemberGainSettingList, memberId);
        //if (rcMemberGainSettingList.size() > 0) {
        //    //有默认规则自动增加
        //    rcMemberGainSettingRecordService.insertByList(rcMemberGainSettingList, memberId);
        //}
        //if (rcMemberGainGradeSettingList.size() > 0) {
        //    //挡位增加
        //    rcMemberGainGradeRecordService.insertByList(rcMemberGainGradeSettingList, memberId);
        //}
        //
        ////后续同步空值record下的数据id
        //rcMemberGainGradeRecordService.updateByList();

        //if (rcMemberFlag.getMemberLevel() != null && !"V0".equals(rcMemberFlag.getMemberLevel())) {
        //    //其他等级，累加
        MemberAccount memberAccount = memberAccountMapper.selectByPrimaryKey(memberId);
        MemberAccount addMemberAccount = new MemberAccount();
        addMemberAccount.setMemberId(memberId);
        addMemberAccount.setUpperAmount(rechargeOrder.getAmount());
        //升级额度变0
        addMemberAccount.setMemberLevelAmount(BigDecimal.ZERO);
        addMemberAccount.setLastUpdatedTime(new Date());
        memberAccountMapper.updateByPrimaryKeySelective(addMemberAccount);
        //}
    }

    /**
     * 用户本次充值增加多少权益金
     */
    public void frozenGiveAccountAdd(RechargeOrder rechargeOrder) {
        Long memberId = rechargeOrder.getMemberId();
        BigDecimal amount = rechargeOrder.getAmount();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");

        //MemberRefundApplyExample memberRefundApplyExample = new MemberRefundApplyExample();
        //memberRefundApplyExample.createCriteria().andStatusEqualTo("4").andMemberIdEqualTo(memberId);
        //List<MemberRefundApply> memberRefundApplyList = memberRefundApplyService.selectByExample(memberRefundApplyExample);
//        OrderRefundApplyExample orderRefundApplyExample = new OrderRefundApplyExample();
//        orderRefundApplyExample.createCriteria().andStatusEqualTo("1").andMemberIdEqualTo(memberId);
//        List<OrderRefundApply> orderRefundApplyList = orderRefundApplyService.selectByExample(orderRefundApplyExample);


        //成功提现次数
        MemberRefundApplyExample memberRefundApplyExample = new MemberRefundApplyExample();
        memberRefundApplyExample.createCriteria().andStatusEqualTo("4").andMemberIdEqualTo(memberId);
        List<MemberRefundApply> memberRefundApplyList = memberRefundApplyService.selectByExample(memberRefundApplyExample);


        MemberInfo memberInfo = memberInfoService.selectByPrimaryKey(memberId);
        CurrentMemberFlagAllVo currentMemberFlagAllVo = rcMemberFlagService.selectCurrentMemberFlagAllVo(memberInfo);


        //提现设置
        TenantTransfer tenantTransfer = tenantTransferService.selectByExample(new TenantTransferExample()).stream().findFirst().orElseGet(() -> null);

        //1.权益金
        if (currentMemberFlagAllVo.getRcMemberLevelVo() != null) {
            RcMemberLevelVo rcMemberLevelVo = currentMemberFlagAllVo.getRcMemberLevelVo();
            List<RcMemberLevelVo.RcMemberGainSettingRecordVo> rcMemberGainSettingRecordVoList = rcMemberLevelVo.getRcMemberGainSettingRecordVos();
            for (RcMemberLevelVo.RcMemberGainSettingRecordVo rcMemberGainSettingRecordVo : rcMemberGainSettingRecordVoList) {

                if (rcMemberGainSettingRecordVo.getRcMemberGainSettingRecord() == null) {
                    logger.info("用户：{}，无数据：{}", memberInfo.getMemberId(), JSON.toJSONString(rcMemberGainSettingRecordVo));
                    continue;
                }
                //                if (rcMemberGainSettingRecordVo.getRcMemberGainSettingRecord() != null
                //                        && rcMemberGainSettingRecordVo.getRcMemberGainSettingRecord().getRefundUnhandsel() != null
                //                        && rcMemberGainSettingRecordVo.getRcMemberGainSettingRecord().getRefundUnhandsel() <= orderRefundApplyList.size()) {
                //                    //1.查询用户退款次数，不能增加权益
                //                    continue;
                //                }

                if (tenantTransfer != null && tenantTransfer.getTransferNoMoney() != null && tenantTransfer.getTransferNoMoney() <= memberRefundApplyList.size()) {
                    //1.查询用户提现次数，不能增加权益
                    continue;
                }

                //1充值送权益金 2生日礼遇(当天)
                if ("1".equals(rcMemberGainSettingRecordVo.getRcMemberGainSettingRecord().getGainType())
                    //|| ("2".equals(rcMemberGainSettingRecordVo.getRcMemberGainSettingRecord().getGainType())
                    //&& format.format(new Date()).equals(format.format(memberInfo.getBirthday())))
                ) {


                    List<RcMemberGainGradeRecord> rcMemberGainGradeRecordList = rcMemberGainSettingRecordVo.getRcMemberGainGradeRecords();
                    //查找数据
                    List<RcMemberGainGradeRecord> rcMemberGainGradeRecordsByCodition = rcMemberGainGradeRecordList.stream().filter(data -> data.getRechargeAmount() != null && data.getRechargeAmount().compareTo(amount) <= 0 && data.getGainAmount() != null && data.getGainAmount().compareTo(BigDecimal.ZERO) != 0).collect(Collectors.toList());
                    if (rcMemberGainGradeRecordsByCodition != null && rcMemberGainGradeRecordsByCodition.size() > 0) {
                        MemberAccount memberAccount = memberAccountMapper.selectByPrimaryKey(memberId);
                        //倒叙取最大值
                        List<RcMemberGainGradeRecord> endData = rcMemberGainGradeRecordsByCodition.stream().sorted(Comparator.comparing(RcMemberGainGradeRecord::getRechargeAmount).reversed()).collect(Collectors.toList());
                        //当前赠送权益金
                        RcMemberGainGradeRecord rcMemberGainGradeRecord = endData.get(0);
                        //直接注入到冻结金
                        MemberAccount newMemberAcount = new MemberAccount();
                        newMemberAcount.setMemberId(memberAccount.getMemberId());
                        newMemberAcount.setFrozenGiveAccount(memberAccount.getFrozenGiveAccount().add(rcMemberGainGradeRecord.getGainAmount()));
                        newMemberAcount.setAllGiveAmount(memberAccount.getAllGiveAmount().add(rcMemberGainGradeRecord.getGainAmount()));
                        newMemberAcount.setLastUpdatedTime(new Date());
                        memberAccountMapper.updateByPrimaryKeySelective(newMemberAcount);

                        logger.info("用户：{}，权益金增加：{}", memberInfo.getMemberId(), JSON.toJSONString(newMemberAcount));
                        //注入记录
                        //3 新增余额变动记录
                        MemberAccountRecord memberAccountRecord = new MemberAccountRecord();
                        memberAccountRecord.setTenantCode(rechargeOrder.getTenantCode());
                        memberAccountRecord.setMemberId(rechargeOrder.getMemberId());
                        memberAccountRecord.setLocalTradeNo(rechargeOrder.getOutTradeNo());
                        //支付的账户类型 0个人钱包 1 企业钱包 2权益金 3收益金
                        memberAccountRecord.setAccountType("2");
                        //记录类型(0会员在线充值,1支出,2转账收入,3分配余额,4后台订单调整,5平台赠送,6积分兑换 7回收金额 8平台钱包充值 9分销返利 10资源占用费 11平台扣费 12 数据迁移 13共享额度变更 14后台退款 15.原路退款 16原路返还 ) 17.先付后退充值 18.先付后退退款
                        memberAccountRecord.setRecordType("0");
                        //本次变更金额
                        memberAccountRecord.setAmount(rcMemberGainGradeRecord.getGainAmount());
                        //累计后的account
                        memberAccountRecord.setResult(memberAccount.getFrozenGiveAccount());
                        StringBuffer sb = new StringBuffer("权益金");
                        memberAccountRecord.setRemark(sb.toString());
                        memberAccountRecord.setCreatedTime(new Date());
                        memberAccountRecord.setLastUpdatedTime(new Date());
                        memberAccountRecordMapper.insertSelective(memberAccountRecord);

                        logger.info("用户：{}，权益金变动记录增加：{}", memberInfo.getMemberId(), JSON.toJSONString(memberAccountRecord));
                    }
                }
            }
        }

    }

    /**
     * 推荐者根据渠道商权益增加收益金
     *
     * @param memberAccount
     */
    public void recommenderChannelAdd(MemberAccount memberAccount, RechargeOrder rechargeOrder) {
        //充值金额
        BigDecimal amount = rechargeOrder.getAmount();
        boolean flag = false;
        MemberInfo memberInfo = memberInfoService.selectByPrimaryKey(memberAccount.getMemberId());
        List<MemberAccountRecord> memberAccountRecordList = memberAccountRecordService.listMemberAccountRecord(memberAccount.getMemberId());


        if (memberAccountRecordList == null || memberAccountRecordList.size() == 0) {
            //用户首次充值
            flag = true;
            logger.info("{}用户首次充值:{},订单:{}", memberAccount.getMemberId(), amount, rechargeOrder.getOutTradeNo());
        } else {
            logger.info("{}用户非首次充值:{},订单:{}", memberAccount.getMemberId(), amount, rechargeOrder.getOutTradeNo());
        }

        if (memberInfo.getRecommenderId() != null) {
            //推荐者
            MemberInfo recommender = memberInfoService.selectByPrimaryKey(memberInfo.getRecommenderId());
            //推荐者权益
            if (recommender != null) {
                CurrentMemberFlagAllVo currentMemberFlagAllVo = rcMemberFlagService.selectCurrentMemberFlagAllVo(recommender);
                if (currentMemberFlagAllVo.getRcChannelLevelVo() != null && currentMemberFlagAllVo.getRcChannelLevelVo().getRcChannelGainRecords().size() > 0) {
                    //存在渠道商权益
                    //RcChannelGainRecord rcChannelGainRecord = currentMemberFlagAllVo
                    //        .getRcChannelLevelVo().getRcChannelGainRecords().stream().filter(data -> "1".equals(data.getGainType())).findFirst().orElseGet(() -> null);
                    RcChannelGainSetting rcChannelGainRecord = currentMemberFlagAllVo.getRcChannelLevelVo().getRcChannelGainRecords().stream().filter(data -> "1".equals(data.getGainType())).findFirst().orElseGet(() -> null);
                    if (flag) {
                        //获取首次充值返现比例数值
                        RcChannelGainSetting rcChannelGainRecordFirst = currentMemberFlagAllVo.getRcChannelLevelVo().getRcChannelGainRecords().stream().filter(data -> "0".equals(data.getGainType())).findFirst().orElseGet(() -> null);
                        if (rcChannelGainRecordFirst != null) {
                            rcChannelGainRecord = rcChannelGainRecordFirst;
                        }

                    }
                    if (rcChannelGainRecord == null || rcChannelGainRecord.getRebateRatio() == null) {
                        return;
                    }
                    //根据规则给渠道商分成
                    recommenderChannelAddByRecord(rcChannelGainRecord, recommender, rechargeOrder, flag);

                }
            }
        }
    }

    /**
     * 金额按照规则返现给推荐者（渠道商用户）
     *
     * @param rcChannelGainRecord
     */
    public void recommenderChannelAddByRecord(RcChannelGainSetting rcChannelGainRecord, MemberInfo recommender, RechargeOrder rechargeOrder, boolean flag) {

        MemberAccount memberAccount = memberAccountMapper.selectByPrimaryKey(recommender.getMemberId());

        //计算比例
        BigDecimal rebateRatio = new BigDecimal(rcChannelGainRecord.getRebateRatio().replace("%", "")).divide(new BigDecimal(100));
        //收益金
        BigDecimal amount = rebateRatio.multiply(rechargeOrder.getAmount()).setScale(2, BigDecimal.ROUND_HALF_UP);

        if (amount.compareTo(BigDecimal.ZERO) == 1) {
            MemberAccount newMemberAccount = new MemberAccount();
            newMemberAccount.setMemberId(recommender.getMemberId());
            newMemberAccount.setIncomeAmount(memberAccount.getIncomeAmount().add(amount));
            newMemberAccount.setAllIncomeAmount(memberAccount.getAllIncomeAmount().add(amount));
            newMemberAccount.setLastUpdatedTime(new Date());
            memberAccountMapper.updateByPrimaryKeySelective(newMemberAccount);
            //memberAcountRecord 收益金记录
            MemberAccountRecord memberAccountRecord = new MemberAccountRecord();
            memberAccountRecord.setTenantCode(recommender.getTenantCode());
            memberAccountRecord.setMemberId(recommender.getMemberId());
            memberAccountRecord.setLocalTradeNo(rechargeOrder.getOutTradeNo());
            //支付的账户类型 0个人钱包 1 企业钱包 2权益金 3收益金
            memberAccountRecord.setAccountType("3");
            //记录类型(0会员在线充值,1支出,2转账收入,3分配余额,4后台订单调整,5平台赠送,6积分兑换 7回收金额 8平台钱包充值 9分销返利 10资源占用费 11平台扣费 12 数据迁移 13共享额度变更 14后台退款 15.原路退款 16原路返还 ) 17.先付后退充值 18.先付后退退款
            memberAccountRecord.setRecordType("0");
            //本次变更金额
            memberAccountRecord.setAmount(amount);
            memberAccountRecord.setResult(memberAccount.getIncomeAmount());
            memberAccountRecord.setChannelType(rcChannelGainRecord.getGainType());
            StringBuffer sb = new StringBuffer("充值提成");
            memberAccountRecord.setRemark(sb.toString());
            memberAccountRecord.setCreatedTime(new Date());
            memberAccountRecord.setLastUpdatedTime(new Date());
            memberAccountRecord.setChannelLevel(rcChannelGainRecord.getChannelLevel());
            memberAccountRecord.setChannelStatus("0");
            memberAccountRecord.setRabeteRatio(Long.valueOf(rcChannelGainRecord.getRebateRatio().replace("%", "")));
            RcSetting rcSetting = rcSettingService.selectByExample(new RcSettingExample()).stream().findFirst().orElseGet(() -> null);
            if (rcSetting != null && rcSetting.getAccountPeriod() != null) {
                Calendar c = Calendar.getInstance();
                c.add(Calendar.DATE, rcSetting.getAccountPeriod());//计算30天后的时间
                memberAccountRecord.setWithdrawTime(c.getTime());
            }


            if (flag) {
                memberAccountRecord.setChannelType("0");
            } else {
                memberAccountRecord.setChannelType("1");
            }

            memberAccountRecordMapper.insertByReturnId(memberAccountRecord);
            // 发送mq 给后台
            mqProducer.send(MqConfig.app_rc_operator_account_record, JSON.toJSONString(memberAccountRecord));
            logger.info("用户：{}，收益金增加：{}", recommender.getMemberId(), JSON.toJSONString(memberAccountRecord));

        } else {
            logger.info("用户：{}，订单收益金四舍五入2位小数少于0不予增加：{}：{}", recommender.getMemberId(), rechargeOrder.getOutTradeNo(), amount);
        }
    }

}
